package cn.idongjia.task.provider.common;

import cn.idongjia.task.common.task.JobToTask;
import cn.idongjia.task.common.task.Task;
import cn.idongjia.task.common.task.TaskResult;
import com.lts.core.commons.concurrent.ConcurrentHashSet;
import com.lts.core.commons.utils.CollectionUtils;
import com.lts.core.domain.Job;
import com.lts.core.domain.JobResult;
import com.lts.jobclient.support.JobCompletedHandler;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by renxianlong on 16/4/7.
 */
public class JobFinishHandler implements JobCompletedHandler {

    private Map<String,TaskFeedBackHandler> handlerMap = new ConcurrentHashMap<>();

    Logger logger = Logger.getLogger(JobFinishHandler.class);

    @Override
    public void onComplete(List<JobResult> jobResults) {
        if(CollectionUtils.isNotEmpty(jobResults)){
            Iterator<JobResult> it = jobResults.iterator();
            while (it.hasNext()){
                JobResult jobResult = it.next();
                Job job = jobResult.getJob();
                TaskResult taskResult = JobToTask.convert(jobResult);
                logger.info("receive feed back:" + taskResult);
                TaskFeedBackHandler handler = handlerMap.get(job.getTaskId());
                if(null != handler){
                    handler.onFeedBack(taskResult);
                }
            }
        }
    }

    public void registHandler(String taskType, TaskFeedBackHandler handler){
        handlerMap.put(taskType,handler);
    }

    public void registHandler(Map<String,TaskFeedBackHandler> handlers){
        handlerMap.putAll(handlers);
    }
}
